#!/usr/bin/env python
# encoding: utf-8
"""
tagmodel.py

Created by AlanYang on 2011-06-20.
Copyright (c) 2011 __MyCompanyName__. All rights reserved.
"""
import sys
import redis
import pymongo
from flask import g

from mongomodel import MongoModel
from application import app

@app.signal_addtagscore.connect
def bumptag(sender,**kv):
    tag = kv.pop('tag',None)
    if not tag:return False
    return TagModel().addtag(tag)
    
def gettags(skip=0,limit=10):
    model = TagModel()
    return model.gettags(skip,limit)
    
def gethottags(skip=0,limit=10):
    return TagModel().getsortedtags(skip,limit)
    
def getdetail(tag):
    return TagModel().getdetail(tag)
    
def getquestions(tag,skip=0,limit=10):
    return TagModel().gettagquestions(tag,skip,limit)

class TagModel(MongoModel):
    """
    tag name in redis zset 
    tag info in mongo cache to redis
    """
    def __init__(self):
        if not getattr(g, 'mongo',None):
            g.mongo = pymongo.Connection(app.config['MONGO_HOST'],app.config['MONGO_PORT'])
        if not getattr(g, 'redis',None):
            g.redis = redis.Redis(app.config['REDIS_HOST'],app.config['REDIS_PORT'],db = app.config['DB_REDIS_TAG'])
        self.__key = 'freeasker:tag:collection'
        self.qset  = g.redis
        MongoModel.__init__(self,g.mongo.freeasker.tag,'_id',g.redis,app.config['TAG_EXPIRE'])
        
    def addtag(self,tag,cnt=1,**kv):
        if kv.has_key('descript'):
            kv[self.pk] = tag
            result = self.save(**kv)
        return self.qset.zincrby(self.__key,tag,cnt)
        
    def gettags(self,skip=0,limit=10):
        return self.qset.zrange(self.__key,skip,limit)
#        return self.qset.zrangebyscore(self.__key,0,sys.maxint,start=skip,num=limit)
        
    def getsortedtags(self,skip=0,limit=10):
        return self.qset.zrevrange(self.__key,skip,limit,True)
        
    def getdetail(self,tag):
        return self.get(**{self.pk:tag})
        
    def gettagquestions(self,tag,skip=0,limit=10):
        _,questions = app.signal_tagquestions.send(__name__,tag = tag,skip = skip,limit = limit)[0]
        return questions
        
    def __len__(self):
        return self.qset.zcard(self.__key)
